<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Advertiser;
use app\common\model\Base;
use app\common\model\Config;
use app\common\model\SmsChannel;
use app\common\model\SmsTemplate;
use think\Model;

/**
 * 短信基类接口
 */
class SmsBaseController extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    protected array $params = [];
    /** @var Base|Model */
    protected $advertiser;
    protected array $config = [];
    protected object $sms_config;
    protected object $channel_config;

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->params = $this->request->param();
        $app_key = $this->params['app_key'] ?? '';
        if (!$app_key) {
            $this->error('参数错误');
        }
        $advertiser = (new Advertiser())->fetch(['key' => $app_key])['data'];
        if (!$advertiser) {
            $this->error('app_key不存在');
        }
        $this->advertiser = $advertiser;
        if (in_array($this->request->action(), ['sendcode', 'sendsms', 'querysmsstatus'])) {
            $sms_key = $this->params['sms_key'] ?? '';
            if (!$sms_key) {
                $this->error('参数错误');
            }
            $sms_config = (new SmsTemplate())->fetch(['key' => $sms_key])['data'];
            if (!$sms_config) {
                $this->error('sms_key不存在');
            }

            $sms_channel = (new SmsChannel())->fetch(['id' => $sms_config['sms_channel_id']])['data'];
            if (!$sms_channel) {
                $this->error('短信渠道配置错误');
            }
            $this->sms_config = $sms_config;
            $this->channel_config = $sms_channel;
        }
        $this->config = (new Config())->where('group', 'sms_config')->column('name,value', 'name');
    }
}
